const {
  http
} = require("../../../utils/apiutils")
const
  util = require("../../../utils/util")

const app = getApp()
Page({

  data: {
    active: 0,
    sh: 0,
    limitTop: 0,
    limitBottom: 0,
    shs: 0,
    statusBar: 0,
    CustomBar: 0,
    canvasShow: false,
    limit: 10,
    itemHeight: 0,
    dataList: [],
    pageNo: 1,
    total: 1,
    latitude: 0,
    longitude: 0,
    action: 0,
    actionCur: {},
    fDataList: [],
    sDataList: [],
    userInfo: {},
    pageSize: 1000,
    swiper: [],
    step1: false,
    step2: false,
    postType: 1,
    shortType: '次单',
    hasFactory: false
  },
  onclickSearch: function () {

    wx.navigateTo({
      url: '/pages/home/pages/search/search',
    })
  },
  //检测活动距离
  scroll: function (e) {
    if (e.detail > this.data.CustomBar) {
      this.setData({
        ts: true,
      })
    } else {
      this.setData({
        ts: false,
      })
    }
    // console.log("---------滑动距离---", e);
  },
  onclickLook: function (e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/home/pages/work/work?id=' + item.id,
    })
  },
  onclickInfo: function () {


    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?ptype=home',
            })
          }
        }
      })
      return;
    }

    if (this.data.action == 1) {
      if (this.data.actionCur.status == 4) {
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 2,
          jobId: this.data.actionCur.jobId,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })

      } else if (this.data.actionCur.status == 3) {
        // console.log("-------到岗打卡-----",item);
        // this.clockIn(item.id);
        var interviewDate = "";
        var str = this.data.actionCur.interviewDate;
        if (str) {
          str = str.substring(0, 19);
          str = str.replace(/-/g, '/');
          let date = new Date(str);
          interviewDate = date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDate().toString(); // 年
        }
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 1,
          jobId: this.data.actionCur.jobId,
          interviewDate: interviewDate,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })
      } else {
        wx.navigateTo({
          url: '/pages/me/pages/action/action?type=3',
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/me/pages/action/action?type=3',
      })
    }

    // if (this.data.action == 1) {
    //   let item = this.data.actionCur;
    //   console.log("--------", item);
    //   let data = {
    //     id: item.id,
    //     name: item.jobName,
    //     workplace: item.workplace,
    //     type: 2,
    //     jobId: item.jobId
    //   }

    //   wx.navigateTo({
    //     url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/me/pages/duty/duty',
    //   })
    // }
  },
  onclickPush: function () {
    // let isTrue = getApp().globalData.check();
    if (!getApp().globalData.userInfo.exist) {
      wx.showModal({
        title: "提示",
        content: "您尚未添加公司信息暂无法使用",
        cancelText: '稍后认证',
        confirmText: '去认证',
        success: function (e) {
          if (e.confirm) {
            wx.navigateTo({
              // url: '/pages/me/pages/companyInfo/companyInfo',
              url: '/pages/me/pages/savecompany/index',
            })
          }
          if (e.cancel) {
            http.laterCertification({}, res => {
              if (res.status == 200) {
                http.userInfo({}, res => {
                  if (res.code == 0) {
                    getApp().globalData.userInfo = res.data;
                  } else {
                    wx.showToast({
                      title: res.message,
                      icon: "none",
                    })
                  }
                }, err => { })
                wx.reLaunch({
                  url: '/pages/tabBar/home/index',
                })
              }
            }, err => { })
          }
        },
      })
      return
    }
    getApp().globalData.playStatus = 1;
    if (getApp().globalData.userInfo.exist) {
      wx.hideTabBar({
        animation: true,
      })
      this.setData({
        step1: true
      })
    }
  },
  toPublish(e) {
    let key = e.currentTarget.dataset.key
    if (key == 1) {
      this.setData({
        shortType: '次单'
      })
    } else if (key == 2) {
      this.setData({
        shortType: '时单'
      })
    } else if (key == 3) {
      this.setData({
        shortType: '日单'
      })
    }
    wx.navigateTo({
      url: `/pages/home/pages/company/company?postType=${this.data.postType}&payType=${this.data.shortType}`,
    })
    this.setData({
      step2: false,
      step1: false
    })
  },
  onclickCell: function (e) {
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?ptype=home',
            })
          }
        }
      })
      return;
    }
    let item = e.currentTarget.dataset.item;
    // if (index % 2 == 0) {
    //   wx.navigateTo({
    //     url: '/pages/home/pages/train/train',
    //   })
    // } else {
    wx.navigateTo({
      url: '/pages/home/pages/work/work?id=' + item.id,
    })
    // }
  },
  onclickZP: function (e) {
    let item = e.currentTarget.dataset.item;
    getApp().globalData.workInfo = item;
    console.log(item)
    wx.navigateTo({
      url: '/pages/home/pages/person/person?workname=' + item.name,
    })
  },
  onclickswiper: function (e) {

    let item = e.currentTarget.dataset.item;
    if (item.video) {
      wx.setStorageSync('video', JSON.stringify(item))
      wx.navigateTo({
        url: '/pages/home/pages/video/video',
      })
    }
    else {
      wx.showToast({
        title: '暂无详细介绍',
        icon: "none",
      })
    }
  },
  //获取已完成的任务列表
  getJob1() {
    var data = {
      "pageNo": this.data.pageNo,
      "pageSize": this.data.pageSize,
      "statusIds": "6",
      coerce: true
    }
    if (!getApp().globalData.exist) return
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getJob(data,
      function (res) {
        wx.hideLoading()
        // console.log("-----已完成任务列表---", res);
        if (res.success) {
          var pageNo = res.data.current;
          var total = res.data.pages;
          var arr = res.data.records;
          that.setData({
            fDataList: arr,
          })
          return
          if (pageNo == 1) {
            that.setData({
              dataList: arr,
              pageNo,
              total
            })
          } else if (pageNo <= total) {
            that.setData({
              dataList: [...that.data.dataList, ...arr],
              pageNo,
              total
            })
          }
        } else {
          wx.showToast({
            title: res.message || '暂无数据',
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  getJob() {
    var data = {
      "pageNo": this.data.pageNo,
      "pageSize": this.data.pageSize,
      "statusIds": "2,3,5,8,9,10",
      coerce: true
    }
    if (!getApp().globalData.exist) return
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getJob(data,
      function (res) {
        wx.hideLoading()
        if (res.success) {
          var pageNo = res.data.current;
          var total = res.data.pages;
          var arr = res.data.records;
          that.setData({
            sDataList: arr,
          })
          return
          arr.forEach(element => {
            if (!that.data.latitude == 0) {
              let ds = util.getDistance(that.data.latitude, that.data.longitude, element.lat, element.lng);
              // console.log("-----------", ds)
              if (element.stationFollow == 1) {
                element.dst = 0
              }
              else {
                element.dst = ds;
              }
              if (ds > 1) {
                element.ds = ds.toFixed(1) + "公里"
              } else {
                element.ds = (ds * 1000).toFixed(0) + "米"
              }
            } else {
              element.ds = "未知"
              element.dst = 0;
            }
          });
          arr = arr.sort(compare("dst"))
          if (pageNo == 1) {
            that.setData({
              dataList: arr,
              pageNo,
              total
            })
          } else if (pageNo <= total) {
            that.setData({
              dataList: [...that.data.dataList, ...arr],
              pageNo,
              total
            })
          }
        } else {
          wx.showToast({
            title: res.message || '暂无数据',
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  onLoad: function (options) {
    // wx.scanCode({
    //   onlyFromCamera: true,
    //   success(res){
    //     console.log(res)
    //   }

    // })
    // setTimeout(()=>{
    //   wx.navigateTo({
    //     url: '/pages/home/pages/person/person',
    //   })
    // },1000)
    wx.getSystemInfo({
      success(res) {
        // console.log(res);
        if (res.platform == "devtools") {
          // getApp().globalData.isDevtool = true;
        }
      }
    })
    // wx.hideShareMenu({
    //   menus: ['shareAppMessage', 'shareTimeline'],
    //   success(res){
    //     console.log(res)
    //   },
    //   fail(err){
    //     console.log(err)
    //   }
    // })
    if (options.rId) {
      getApp().globalData.share_id = options.rId || '';
    }
    // this.setData({
    //   userInfo: getApp().globalData.userInfo,
    //   hasFactory: !getApp().globalData.exist ? false : true
    // })
    // console.log(999999999999,getApp().globalData)
    let _this = this;
    http.carousel({}, function (res) {
      if (res.code == 0) {
        wx.nextTick(() => {
          _this.setData({
            swiper: res.data
          })
          // console.log(_this.data.swiper)
        })
      }
    }, function () {

    })

  },
  getcarousel: function () {
    var that = this;
    http.getcarousel({},
      function (res) {
        console.log("---轮播图-", res);
        if (res.code == 0) {
          var arr = res.data;
          that.setData({
            imgList: arr,
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onReady: function () {

  },
  change: function (e) {
    this.setData({
      active: e.detail.index
    })
  },

  getclockInInfo: function () {
    var data = {
      "pageNo": 1,
      "pageSize": this.data.pageSize,
      "statusList": "3,4",
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getregistration(data,
      function (res) {
        wx.hideLoading()
        console.log("------报名岗位列表---", res);
        if (res.code == 0) {
          var arr = res.data.records;
          if (arr.length == 1) {
            that.setData({
              actionCur: arr[0],
              action: 1
            })
          } else if (arr.length > 0) {
            that.setData({
              action: 2
            })
          }
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  bindscrolltolower: function () {
    if (this.data.pageNo == this.data.total) {
      wx.showToast({
        title: '没有更多岗位了',
        icon: "none",
      })
    }
    else {
      this.data.pageNo = this.data.pageNo + 1;
      this.getJob()
    }

  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.data.latitude = res.latitude;
        that.data.longitude = res.longitude;
        console.log("-----用户位置信息--", res)
        that.getJob();
        that.getJob1();
      },
      fail: function (res) {
        wx.showToast({
          title: '您没有开启定位服务无法计算距离',
          icon: "none"
        })
        that.getJob();
      }
    })
    return
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //没授权

          return
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            confirmColor: '#f16765',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: data => {
                    if (data.authSetting["scope.userLocation"]) {
                      // 调用百度地图，获取位置信息(就是经纬度转换成地址)
                      wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                          console.log(res);
                          that.data.latitude = res.latitude;
                          that.data.longitude = res.longitude;
                          that.getJob();
                        },
                      })
                    }
                  }
                })
              } else {
                that.getJob();
              }
            }
          })
        } else { //已授权
          //做一些事情...

          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              that.data.latitude = res.latitude;
              that.data.longitude = res.longitude;
              console.log("-----用户位置信息--", res)
              that.getJob();
            },
            fail: function (res) {
              wx.showToast({
                title: '您没有开启定位服务无法计算距离',
                icon: "none"
              })
              that.getJob();
            }
          })
        }
      }
    })
  },
  onShow: function () {
    wx.showTabBar({
      animation: true,
    })
    // console.log("------",getApp().globalData)
    var that = this;
    let CustomBar = app.globalData.CustomBar;
    let statusBar = app.globalData.statusBar
    this.setData({
      CustomBar: CustomBar - statusBar,
      statusBar: statusBar,
      userInfo: getApp().globalData.userInfo,
      hasFactory: !getApp().globalData.exist ? false : true
    })
    wx.getSystemInfo({
      success: (result) => {
        var spx = 415 / 750 * result.windowWidth;
        that.setData({
          sh: result.windowHeight - CustomBar,
          shs: result.windowHeight - CustomBar - spx,
        })
      },
    })
    if (this.data.userInfo && this.data.userInfo.exist != "0") {
      this.getComInfo()
    }
    // this.setData({
    //   hasFactory: !getApp().globalData.exist ? false : true
    // })
  },

  getComInfo: function () {
    let data = {}
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getComInfo(data,
      function (res) {
        wx.hideLoading()
        // console.log("-----已完成任务列表---", res);
        if (res.success) {
          if (res.data && res.data.id) {
            getApp().globalData.factoryInfo = res.data
          }
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  toVideo(e) {
    let url = e.currentTarget.dataset.item.video;
    wx.navigateTo({
      // url: '../../home/pages/video/video?url='+url,
      url: '../../home/pages/videolist/index?url=' + url,
    })
  },
  toqy() {
    wx.navigateTo({
      url: '/pages/me/pages/savecompany/index',
    })
  },
  tojob(e) {
    let key = e.currentTarget.dataset.key;
    // 1进行中  2 已完成
    wx.navigateTo({
      url: '../playing/index?type=' + key,
    })
  },
  showCode() {
    wx.previewImage({
      urls: ['http://linghuoimage.xbbzp.com/FutnHjJ8ql38XMaIwBePZ-PCg7xz'],
      // urls: ['http://linghuoimage.xbbzp.com/Fo7Wv7FFziwAvH8fFDeFSw_CetA3'],
    })
  },
  closeStep() {
    this.setData({
      step1: false,
      step2: false
    })
    wx.showTabBar({
      animation: true,
    })
  },
  changePostType(e) {
    let key = e.currentTarget.dataset.key;
    if (key == 2) {
      wx.navigateTo({
        url: `/pages/home/pages/company/company?postType=2`,
      })
      this.setData({
        step2: false,
        step1: false,
      })
      return
    }
    this.setData({
      step2: true,
      step1: false,
      shortType: '次单',
      postType: e.currentTarget.dataset.key
    })
  },
  scrollChange(e) {
    // ['次单','时单','日单']
    this.setData({
      shortType: ['次单', '时单', '日单'][e.detail.value]
    })
  },
  togoods() {
    wx.navigateTo({
      url: '/pages/home/pages/searchgoods/searchcar',
      fail(err) {
        console.log(err)
      }
    })
  }
})

function compare(property) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}